﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace TireService.Data
{
    public class ContainerCargoRoomBLL
    {
        public int? ReturnNearestContainerCargoRoomId(TireServiceDB db, float? latitude, float? longitude)
        {
            int? containercargoroomid = null;

            try
            {
                containercargoroomid = db.NearestContainer(latitude, longitude).OrderBy(p => p.Distance).OrderBy(p => p.ContainerCargoRoomId).First().ContainerCargoRoomId;
            }
            catch (Exception ex)
            {
                try
                {
                    // Error occured, random free cargoroom will be assigned
                    containercargoroomid = db.GetContainerCargoRoomTireSetViews().Where(p => p.TireSetId == null).OrderBy(p => p.CargoRoomNumber).First().ContainerCargoRoomId;
                }
                catch (Exception)
                {
                    // Error occured, no free cargorooms available - create one and assign it
                    try
                    {
                        TireServiceDB db2 = new TireServiceDB();

                        Container container = db2.GetContainers().First();

                        ContainerCargoRoom cargoroom = new ContainerCargoRoom();
                        container.ContainerCargoRooms.Add(cargoroom);
                        cargoroom.CargoRoomNumber = db2.GetLastContainerCargoRoomNumber(container.ContainerId) + 1;

                        db2.AddContainerCargoRoom(cargoroom);

                        db2.SubmitChanges();

                        containercargoroomid = cargoroom.ContainerCargoRoomId;

                        db2.Dispose();

                        // TODO: write code that sends email to system admin
                        //// Send email to mobil hjulskift message on automated process
                        //string emailaddress = Convert.ToString(ConfigurationManager.AppSettings["EmailAddress"]);
                        //bool test = Convert.ToBoolean(Convert.ToByte(ConfigurationManager.AppSettings["TestEnvironmentOn"]));
                        //string message = String.Format("Systemet har selv ved oprettelse af kunden oprettet en lagerplads<br><br>Lagerlokation Id: {0}", cargoroom.ContainerCargoRoomId.ToString());

                        //Shared email = new Shared();
                        //email.SendEmail(emailaddress, emailaddress, message, "Manglende lagerpladser", true, test, null);
                    }
                    catch (Exception)
                    {
                        // Error occured again - not handled
                    }
                }
            }

            return containercargoroomid;
        }
    }
}
